import { ref } from 'vue';

export interface JsonData {
  // 定义你的 JSON 数据结构
  [key: string]: any;
}

export function useJsonService() {
  const error = ref<string | null>(null);
  const loading = ref<boolean>(false);

  const fetchJson = (filePath: string): Promise<JsonData | null> => {
    loading.value = true;
    error.value = null;


    return new Promise((resolve, reject) => {
      fetch(filePath)
        .then((response) => {
          if (!response.ok) throw new Error('Network response was not ok');
          return response.json();
        })
        .then((resData) => {
          // console.log('读取 json 数据', resData);
          resolve(resData);
        })
        .catch((err) => {
          error.value = err instanceof Error ? err.message : 'Unknown error';
          console.error('Error loading JSON:', err);
          reject(err);
        })
        .finally(() => {
          loading.value = false;
        });
    });
  

    // try {
    //   const response = await fetch(filePath);
    //   if (!response.ok) throw new Error('Network response was not ok');
    //   const resData = await response.json();
    //   console.log('读取 json 数据', resData);
    //   return resData
    // } catch (err) {
    //   error.value = err instanceof Error ? err.message : 'Unknown error';
    //   console.error('Error loading JSON:', err);
    // } finally {
    //   loading.value = false;
    // }
    // return null;
  };

  const saveJson = (fileName: string, data: JsonData): void => {
    try {
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Download failed';
      console.error('Error downloading JSON:', err);
    }
  };

  return {
    error,
    loading,
    fetchJson,
    saveJson,
  };
}